package com.baosight.risk.web.xtdc;


import com.baosight.risk.api.xtdc.XtdcAttachService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.file.FileManager;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.ReadProperties;
import com.baosight.risk.service.xtdc.entity.XtdcAttach;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.InputStream;
import java.util.*;


/**
 * 作者： lishaoqing
 */
@Slf4j
@RestController
@RequestMapping("/xtdc/file")
@Api(value = "附件", produces = MediaType.APPLICATION_JSON)
public class FileController extends BaseController {

    @Autowired
    private FileManager fileManager;

    private String prefix = "xtdc/file";

    /**
     * 磁盘存储路径
     */
    private final String File_PATH = ReadProperties.getValueString("projectServerFilePath");

    @Autowired
    private XtdcAttachService xtdcAttachService;

    /**
     * 分页查询数据,模糊查询
     *
     * @param filed
     * @return
     */
    @GetMapping("list")
    public AjaxResult list(@RequestParam(value = "fileName", required = false) String filed) {
        startPage("create_time", "desc");
        return getResultPage(xtdcAttachService.selectField(filed));
    }

    @ApiOperation("根据id查询附件")
    @GetMapping("listById")
    public AjaxResult getListById(@RequestParam("id") String id) {
        return success(xtdcAttachService.selectById(id));
    }


    @ApiOperation("根据来源id查询附件")
    @GetMapping("listByResource")
    public AjaxResult getListByResource(@RequestParam("sourceGuid") String sourceGuid) {
        return success(xtdcAttachService.selectBySource(sourceGuid));
    }

    @ApiOperation("根据来源id查询附件")
    @GetMapping("listByResourceAndModel")
    public AjaxResult getListBySourceAndModel(String sourceGuid, String sourceModel) {
        return success(xtdcAttachService.selectBySourceAndModel(sourceGuid, sourceModel));
    }

    @ApiOperation("删除资源")
    @PostMapping("deleteResource")
    public AjaxResult deleteResource(@RequestBody List<String> ids) {
        log.info("删除资源：{}", ids.toString());
        if (CollectionUtils.isNotEmpty(ids)) {
            Integer integer = xtdcAttachService.deleteResourceByIds(ids);
            return toAjax(integer);
        }
        return error("删除失败！");

    }

    @ApiOperation("上传文件")
    @PostMapping("uploadFile")
    public AjaxResult upload(HttpServletRequest request) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();

        //转换request
        // 使用Spring的MultipartResolver进行解析
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        commonsMultipartResolver.setDefaultEncoding("UTF-8");
        // 确保请求是multipart类型
        if (!commonsMultipartResolver.isMultipart(request)) {
            return AjaxResult.error("请求不是multipart类型");
        }
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart(request);
        if (multipartRequest == null) {
            return AjaxResult.error("文件解析失败");
        }
        //获取附件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (fileMap.size() == 0){
            fileMap=((DefaultMultipartHttpServletRequest) request).getFileMap();
        }


        //获取页面传参
        String folderId = multipartRequest.getParameter("folderId");
        String businessCode = multipartRequest.getParameter("businessCode");
        String resourceId = UUID.randomUUID().toString();
        Date now = new Date();
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            for (String key : fileMap.keySet()) {
                MultipartFile multipartFile = fileMap.get(key);
                InputStream inputStream = multipartFile.getInputStream();
                String filename = multipartFile.getOriginalFilename();
                long fileSize = multipartFile.getSize();
                FileManager.Config config = fileManager.getConfig();
                config.setInputStream(inputStream);
                config.setFilename(filename);
                config.setBusinessCode(businessCode);
                //生成目录
                fileManager.generateDir(config);
                String filepath = fileManager.validName(config);
                //保存文件到磁盘
                multipartFile.transferTo(new File(filepath));
                Map<String, Object> map = new HashMap<>();
                map.put("filename", config.getFilename());
                map.put("fileSize", fileSize);
                map.put("filepath", filepath);
                list.add(map);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("任务中心-资源共享：上传附件失败！");
            return AjaxResult.error();
        }
        for (Map<String, Object> map : list) {
            String filename = (String) map.get("filename");
            long fileSize = (long) map.get("fileSize");
            String filepath = (String) map.get("filepath");

            String fileType = "file";
            int indx = filename.lastIndexOf(".");
            if (indx > 0 && indx < filename.length() - 1) {
                fileType = filename.substring(indx + 1).toLowerCase();
            }
            //存入数据库==注意teamId
            XtdcAttach attach = (XtdcAttach) BeanUtils.initBean(new XtdcAttach());
            attach.setExt5(getUser().getUserDesc());
            attach.setFileName(filename);
            attach.setFilePath(filepath);
            attach.setFileSize(fileSize);
            attach.setFileType(fileType);
            attach.setFolderId(folderId);
            attach.setSourceGuid(attach.getId());
            xtdcAttachService.insert(attach);
        }
        return success();
    }

    @PostMapping("delete")
    @Log(title = "文件删除", businessType = BusinessType.DELETE)
    public AjaxResult delete(@RequestBody List<String> ids) {
        List<String> idlist = JSONArray.fromObject(ids);
        List<XtdcAttach> filelist = xtdcAttachService.selectByIds(idlist);
        AjaxResult result = toAjax(xtdcAttachService.deleteByIds(idlist));
        for (XtdcAttach file : filelist) {
            boolean delete = new File(file.getFilePath()).delete();
//            System.out.println(delete);
        }
        return result;
    }

    /**
     * 自定义prefix(1)(2)(3)命名规则解决文件名重复的问题
     */
    private String generatePath(String filename) {
        String result = "";
        String prefix = "";
        String suffix = "";
        int indx = filename.lastIndexOf(".");
        if (indx > 0 && indx < filename.length() - 1) {
            prefix = filename.substring(0, indx);
            suffix = filename.substring(indx, filename.length());
        }
        File file = new File(generateDir() + "/" + filename);
        String regex = prefix.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)") + "\\(\\d+\\)+";
        int maxId = 0;
        if (file.exists()) {
            String[] list = file.getParentFile().list();
            String maxprefix = prefix + "(0)";
            for (String tmpprefix : list) {
                tmpprefix = tmpprefix.substring(0, tmpprefix.lastIndexOf("."));
                if (tmpprefix.matches(regex)) {
                    int id = Integer.parseInt(tmpprefix.substring(tmpprefix.lastIndexOf("(") + 1, tmpprefix.lastIndexOf(")")));
                    maxId = Integer.parseInt(maxprefix.substring(maxprefix.lastIndexOf("(") + 1, maxprefix.lastIndexOf(")")));
                    if (id > maxId) {
                        maxprefix = tmpprefix;
                        maxId = id;
                    }
                }
            }
            if (maxprefix.equals(prefix)) {
                result = prefix + "(" + 1 + ")" + suffix;
            } else {
                result = prefix + "(" + (maxId + 1) + ")" + suffix;
            }
            return generateDir() + "/" + result;
        }
        return generateDir() + "/" + filename;
    }

    /**
     * 年/月/日的格式生成文件夹
     */
    private String generateDir() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);

        String dirPath = File_PATH + year + "/" + month + "/" + date;

        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }

    @ApiOperation("新增资源带附件")
    @PostMapping("uploadResource")
    public AjaxResult uploadResource(HttpServletRequest request) {
        XtzyUser sysUser = getUser();
        String userCode = sysUser.getUserCode();

        //转换request
        ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
        //获取页面传参
        String resourceName = multipartRequest.getParameter("resourceName");
        String resourceDesc = multipartRequest.getParameter("resourceDesc");
        String businessCode = multipartRequest.getParameter("businessCode");
        String folderId = multipartRequest.getParameter("folderId");
        Date now = new Date();
        List<Map<String, Object>> list = new ArrayList<>();
        //获取附件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        try {
            for (String key : fileMap.keySet()) {
                MultipartFile multipartFile = fileMap.get(key);
                InputStream inputStream = multipartFile.getInputStream();
                String filename = multipartFile.getOriginalFilename();
                long fileSize = multipartFile.getSize();

                FileManager.Config config = fileManager.getConfig();
                config.setInputStream(inputStream);
                config.setBusinessCode(businessCode);
                config.setFilename(filename);

                //生成目录
                String dir = fileManager.generateDir(config);
                String filepath = dir + "/" + filename;
                //保存文件到磁盘
                multipartFile.transferTo(new File(filepath));
                Map<String, Object> map = new HashMap<>();
                map.put("filename", filename);
                map.put("fileSize", fileSize);
                map.put("filepath", filepath);
                list.add(map);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("任务中心-资源共享：上传附件失败！");
            return AjaxResult.error();
        }


        for (Map<String, Object> map : list) {
            String filename = (String) map.get("filename");
            long fileSize = (long) map.get("fileSize");
            String filepath = (String) map.get("filepath");

            String fileType = "file";
            int indx = filename.lastIndexOf(".");
            if (indx > 0 && indx < filename.length() - 1) {
                fileType = filename.substring(indx + 1).toLowerCase();
            }
            XtdcAttach attach = (XtdcAttach) BeanUtils.initBean(new XtdcAttach());
            attach.setFileName(filename);
            attach.setFilePath(filepath);
            attach.setFileSize(fileSize);
            attach.setFileType(fileType);
            attach.setFolderId(folderId);
            //文件
            attach.setFileStatus("0");
            xtdcAttachService.insert(attach);
        }
        return success();
    }

    @GetMapping("deleteFile")
    public AjaxResult deleteFile(@RequestParam("teamId") String teamId, @RequestParam("fileId") String fileId) {
        Integer integer = xtdcAttachService.deleteById(teamId, fileId);
        if (integer == 0) {
            return error("没有权限删除文件！");
        }
        return success();
    }

    @GetMapping("report")
    public AjaxResult selectReport(XtdcAttach file,String manageCompCode) {
        startPage("create_time", "desc");
        return getResultPage(xtdcAttachService.selectReport(file,manageCompCode));
    }

}
